home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 3: Developer Tools / Linux Cubed Series 3 - Developer Tools.iso / utils / file / fileutil.13 / fileutil / fileutils-3.13 / src / mv.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-07-06  |  11.5 KB  |  497 lines

  1. /* mv -- move or rename files
  2.    Copyright (C) 86, 89, 90, 91, 95, 1996 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software Foundation,
  16.    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
  17.  
  18. /* Options:
  19.    -f, --force        Assume a 'y' answer to all questions it would
  20.             normally ask, and not ask the questions.
  21.  
  22.    -i, --interactive    Require confirmation from the user before
  23.             performing any move that would destroy an
  24.             existing file.
  25.  
  26.    -u, --update        Do not move a nondirectory that has an
  27.             existing destination with the same or newer
  28.             modification time.
  29.  
  30.    -v, --verbose        List the name of each file as it is moved, and
  31.             the name it is moved to.
  32.  
  33.    -b, --backup
  34.    -S, --suffix
  35.    -V, --version-control
  36.             Backup file creation.
  37.  
  38.    Written by Mike Parker and David MacKenzie */
  39.  
  40. #ifdef _AIX
  41.  #pragma alloca
  42. #endif
  43.  
  44. #include <config.h>
  45. #include <stdio.h>
  46. #include <getopt.h>
  47. #include <sys/types.h>
  48.  
  49. #include "system.h"
  50. #include "backupfile.h"
  51. #include "error.h"
  52.  
  53. #ifdef HAVE_LCHOWN
  54. # define chown(PATH, OWNER, GROUP) lchown(PATH, OWNER, GROUP)
  55. #endif
  56.  
  57. #ifndef _POSIX_VERSION
  58. uid_t geteuid ();
  59. #endif
  60.  
  61. char *basename ();
  62. enum backup_type get_version ();
  63. int isdir ();
  64. int yesno ();
  65. int safe_read ();
  66. int full_write ();
  67. void strip_trailing_slashes ();
  68. int euidaccess ();
  69. char *stpcpy ();
  70.  
  71. /* The name this program was run with. */
  72. char *program_name;
  73.  
  74. /* If nonzero, query the user before overwriting files. */
  75. static int interactive;
  76.  
  77. /* If nonzero, do not query the user before overwriting unwritable
  78.    files. */
  79. static int override_mode;
  80.  
  81. /* If nonzero, do not move a nondirectory that has an existing destination
  82.    with the same or newer modification time. */
  83. static int update = 0;
  84.  
  85. /* If nonzero, list each file as it is moved. */
  86. static int verbose;
  87.  
  88. /* If nonzero, stdin is a tty. */
  89. static int stdin_tty;
  90.  
  91. /* This process's effective user ID.  */
  92. static uid_t myeuid;
  93.  
  94. /* FIXME */
  95. static struct stat dest_stats, source_stats;
  96.  
  97. /* If nonzero, display usage information and exit.  */
  98. static int show_help;
  99.  
  100. /* If nonzero, print the version on standard output and exit.  */
  101. static int show_version;
  102.  
  103. static struct option const long_options[] =
  104. {
  105.   {"backup", no_argument, NULL, 'b'},
  106.   {"force", no_argument, NULL, 'f'},
  107.   {"interactive", no_argument, NULL, 'i'},
  108.   {"suffix", required_argument, NULL, 'S'},
  109.   {"update", no_argument, &update, 1},
  110.   {"verbose", no_argument, &verbose, 1},
  111.   {"version-control", required_argument, NULL, 'V'},
  112.   {"help", no_argument, &show_help, 1},
  113.   {"version", no_argument, &show_version, 1},
  114.   {NULL, 0, NULL, 0}
  115. };
  116.  
  117. /* If PATH is an existing directory, return nonzero, else 0.  */
  118.  
  119. static int
  120. is_real_dir (char *path)
  121. {
  122.   struct stat stats;
  123.  
  124.   return lstat (path, &stats) == 0 && S_ISDIR (stats.st_mode);
  125. }
  126.  
  127. /* Copy regular file SOURCE onto file DEST.
  128.    Return 1 if an error occurred, 0 if successful. */
  129.  
  130. static int
  131. copy_reg (char *source, char *dest)
  132. {
  133.   int ifd;
  134.   int ofd;
  135.   char buf[1024 * 8];
  136.   int len;            /* Number of bytes read into `buf'. */
  137.  
  138.   if (!S_ISREG (source_stats.st_mode))
  139.     {
  140.       error (0, 0, _("cannot move `%s' across filesystems: Not a regular file"),
  141.          source);
  142.       return 1;
  143.     }
  144.  
  145.   if (unlink (dest) && errno != ENOENT)
  146.     {
  147.       error (0, errno, _("cannot remove `%s'"), dest);
  148.       return 1;
  149.     }
  150.  
  151.   ifd = open (source, O_RDONLY, 0);
  152.   if (ifd < 0)
  153.     {
  154.       error (0, errno, "%s", source);
  155.       return 1;
  156.     }
  157.   ofd = open (dest, O_WRONLY | O_CREAT | O_TRUNC, 0600);
  158.   if (ofd < 0)
  159.     {
  160.       error (0, errno, "%s", dest);
  161.       close (ifd);
  162.       return 1;
  163.     }
  164.  
  165.   while ((len = safe_read (ifd, buf, sizeof (buf))) > 0)
  166.     {
  167.       if (full_write (ofd, buf, len) < 0)
  168.     {
  169.       error (0, errno, "%s", dest);
  170.       close (ifd);
  171.       close (ofd);
  172.       unlink (dest);
  173.       return 1;
  174.     }
  175.     }
  176.   if (len < 0)
  177.     {
  178.       error (0, errno, "%s", source);
  179.       close (ifd);
  180.       close (ofd);
  181.       unlink (dest);
  182.       return 1;
  183.     }
  184.  
  185.   if (close (ifd) < 0)
  186.     {
  187.       error (0, errno, "%s", source);
  188.       close (ofd);
  189.       return 1;
  190.     }
  191.   if (close (ofd) < 0)
  192.     {
  193.       error (0, errno, "%s", dest);
  194.       return 1;
  195.     }
  196.  
  197.   /* chown turns off set[ug]id bits for non-root,
  198.      so do the chmod last.  */
  199.  
  200.   /* Try to copy the old file's modtime and access time.  */
  201.   {
  202.     struct utimbuf tv;
  203.  
  204.     tv.actime = source_stats.st_atime;
  205.     tv.modtime = source_stats.st_mtime;
  206.     if (utime (dest, &tv))
  207.       {
  208.     error (0, errno, "%s", dest);
  209.     return 1;
  210.       }
  211.   }
  212.  
  213.   /* Try to preserve ownership.  For non-root it might fail, but that's ok.
  214.      But root probably wants to know, e.g. if NFS disallows it.  */
  215.   if (chown (dest, source_stats.st_uid, source_stats.st_gid)
  216.       && (errno != EPERM || myeuid == 0))
  217.     {
  218.       error (0, errno, "%s", dest);
  219.       return 1;
  220.     }
  221.  
  222.   if (chmod (dest, source_stats.st_mode & 07777))
  223.     {
  224.       error (0, errno, "%s", dest);
  225.       return 1;
  226.     }
  227.  
  228.   return 0;
  229. }
  230.  
  231. /* Move SOURCE onto DEST.  Handles cross-filesystem moves.
  232.    If DEST is a directory, SOURCE must be also.
  233.    Return 0 if successful, 1 if an error occurred.  */
  234.  
  235. static int
  236. do_move (char *source, char *dest)
  237. {
  238.   char *dest_backup = NULL;
  239.  
  240.   if (lstat (source, &source_stats) != 0)
  241.     {
  242.       error (0, errno, "%s", source);
  243.       return 1;
  244.     }
  245.  
  246.   if (lstat (dest, &dest_stats) == 0)
  247.     {
  248.       if (source_stats.st_dev == dest_stats.st_dev
  249.       && source_stats.st_ino == dest_stats.st_ino)
  250.     {
  251.       error (0, 0, _("`%s' and `%s' are the same file"), source, dest);
  252.       return 1;
  253.     }
  254.  
  255.       if (S_ISDIR (dest_stats.st_mode))
  256.     {
  257.       error (0, 0, _("%s: cannot overwrite directory"), dest);
  258.       return 1;
  259.     }
  260.  
  261.       if (!S_ISDIR (source_stats.st_mode) && update
  262.       && source_stats.st_mtime <= dest_stats.st_mtime)
  263.     return 0;
  264.  
  265.       if (!override_mode && (interactive || stdin_tty)
  266.       && euidaccess (dest, W_OK))
  267.     {
  268.       fprintf (stderr, _("%s: replace `%s', overriding mode %04o? "),
  269.            program_name, dest,
  270.            (unsigned int) (dest_stats.st_mode & 07777));
  271.       if (!yesno ())
  272.         return 0;
  273.     }
  274.       else if (interactive)
  275.     {
  276.       fprintf (stderr, _("%s: replace `%s'? "), program_name, dest);
  277.       if (!yesno ())
  278.         return 0;
  279.     }
  280.  
  281.       if (backup_type != none)
  282.     {
  283.       char *tmp_backup = find_backup_file_name (dest);
  284.       if (tmp_backup == NULL)
  285.         error (1, 0, _("virtual memory exhausted"));
  286.       dest_backup = (char *) alloca (strlen (tmp_backup) + 1);
  287.       strcpy (dest_backup, tmp_backup);
  288.       free (tmp_backup);
  289.       if (rename (dest, dest_backup))
  290.         {
  291.           if (errno != ENOENT)
  292.         {
  293.           error (0, errno, _("cannot backup `%s'"), dest);
  294.           return 1;
  295.         }
  296.           else
  297.         dest_backup = NULL;
  298.         }
  299.     }
  300.     }
  301.   else if (errno != ENOENT)
  302.     {
  303.       error (0, errno, "%s", dest);
  304.       return 1;
  305.     }
  306.  
  307.   if (verbose)
  308.     printf ("%s -> %s\n", source, dest);
  309.  
  310.   if (rename (source, dest) == 0)
  311.     {
  312.       return 0;
  313.     }
  314.  
  315.   if (errno != EXDEV)
  316.     {
  317.       error (0, errno, _("cannot move `%s' to `%s'"), source, dest);
  318.       goto un_backup;
  319.     }
  320.  
  321.   /* rename failed on cross-filesystem link.  Copy the file instead. */
  322.  
  323.   if (copy_reg (source, dest))
  324.     goto un_backup;
  325.  
  326.   if (unlink (source))
  327.     {
  328.       error (0, errno, _("cannot remove `%s'"), source);
  329.       return 1;
  330.     }
  331.  
  332.   return 0;
  333.  
  334.  un_backup:
  335.   if (dest_backup)
  336.     {
  337.       if (rename (dest_backup, dest))
  338.     error (0, errno, _("cannot un-backup `%s'"), dest);
  339.     }
  340.   return 1;
  341. }
  342.  
  343. /* Move file SOURCE onto DEST.  Handles the case when DEST is a directory.
  344.    Return 0 if successful, 1 if an error occurred.  */
  345.  
  346. static int
  347. movefile (char *source, char *dest)
  348. {
  349.   strip_trailing_slashes (source);
  350.  
  351.   if ((dest[strlen (dest) - 1] == '/' && !is_real_dir (source))
  352.       || isdir (dest))
  353.     {
  354.       /* Target is a directory; build full target filename. */
  355.       char *base;
  356.       char *new_dest;
  357.  
  358.       base = basename (source);
  359.       /* Remove a (single) trailing slash if there is at least one.  */
  360.       if (dest[strlen (dest) - 1] == '/')
  361.         dest[strlen (dest) - 1] = '\0';
  362.       new_dest = (char *) alloca (strlen (dest) + 1 + strlen (base) + 1);
  363.       stpcpy (stpcpy (stpcpy (new_dest, dest), "/"), base);
  364.       return do_move (source, new_dest);
  365.     }
  366.   else
  367.     return do_move (source, dest);
  368. }
  369.  
  370. static void
  371. usage (int status)
  372. {
  373.   if (status != 0)
  374.     fprintf (stderr, _("Try `%s --help' for more information.\n"),
  375.          program_name);
  376.   else
  377.     {
  378.       printf (_("\
  379. Usage: %s [OPTION]... SOURCE DEST\n\
  380.   or:  %s [OPTION]... SOURCE... DIRECTORY\n\
  381. "),
  382.           program_name, program_name);
  383.       printf (_("\
  384. Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.\n\
  385. \n\
  386.   -b, --backup                 make backup before removal\n\
  387.   -f, --force                  remove existing destinations, never prompt\n\
  388.   -i, --interactive            prompt before overwrite\n\
  389.   -u, --update                 move only older or brand new files\n\
  390.   -v, --verbose                explain what is being done\n\
  391.   -S, --suffix=SUFFIX          override the usual backup suffix\n\
  392.   -V, --version-control=WORD   override the usual version control\n\
  393.       --help                   display this help and exit\n\
  394.       --version                output version information and exit\n\
  395. \n\
  396. "));
  397.       printf (_("\
  398. The backup suffix is ~, unless set with SIMPLE_BACKUP_SUFFIX.  The\n\
  399. version control may be set with VERSION_CONTROL, values are:\n\
  400. \n\
  401.   t, numbered     make numbered backups\n\
  402.   nil, existing   numbered if numbered backups exist, simple otherwise\n\
  403.   never, simple   always make simple backups\n"));
  404.     }
  405.   exit (status);
  406. }
  407.  
  408. int
  409. main (int argc, char **argv)
  410. {
  411.   int c;
  412.   int errors;
  413.   int make_backups = 0;
  414.   char *version;
  415.  
  416.   program_name = argv[0];
  417.   setlocale (LC_ALL, "");
  418.   bindtextdomain (PACKAGE, LOCALEDIR);
  419.   textdomain (PACKAGE);
  420.  
  421.   version = getenv ("SIMPLE_BACKUP_SUFFIX");
  422.   if (version)
  423.     simple_backup_suffix = version;
  424.   version = getenv ("VERSION_CONTROL");
  425.  
  426.   myeuid = geteuid ();
  427.   interactive = override_mode = verbose = update = 0;
  428.   errors = 0;
  429.  
  430.   while ((c = getopt_long (argc, argv, "bfiuvS:V:", long_options, (int *) 0))
  431.      != EOF)
  432.     {
  433.       switch (c)
  434.     {
  435.     case 0:
  436.       break;
  437.     case 'b':
  438.       make_backups = 1;
  439.       break;
  440.     case 'f':
  441.       interactive = 0;
  442.       override_mode = 1;
  443.       break;
  444.     case 'i':
  445.       interactive = 1;
  446.       override_mode = 0;
  447.       break;
  448.     case 'u':
  449.       update = 1;
  450.       break;
  451.     case 'v':
  452.       verbose = 1;
  453.       break;
  454.     case 'S':
  455.       simple_backup_suffix = optarg;
  456.       break;
  457.     case 'V':
  458.       version = optarg;
  459.       break;
  460.     default:
  461.       usage (1);
  462.     }
  463.     }
  464.  
  465.   if (show_version)
  466.     {
  467.       printf ("mv - %s\n", PACKAGE_VERSION);
  468.       exit (0);
  469.     }
  470.  
  471.   if (show_help)
  472.     usage (0);
  473.  
  474.   if (argc < optind + 2)
  475.     {
  476.       error (0, 0, "%s", (argc == optind
  477.               ? _("missing file arguments")
  478.               : _("missing file argument")));
  479.       usage (1);
  480.     }
  481.  
  482.   if (make_backups)
  483.     backup_type = get_version (version);
  484.  
  485.   stdin_tty = isatty (STDIN_FILENO);
  486.  
  487.   if (argc > optind + 2 && !isdir (argv[argc - 1]))
  488.     error (1, 0,
  489.        _("when moving multiple files, last argument must be a directory"));
  490.  
  491.   /* Move each arg but the last onto the last. */
  492.   for (; optind < argc - 1; ++optind)
  493.     errors |= movefile (argv[optind], argv[argc - 1]);
  494.  
  495.   exit (errors);
  496. }
  497.